<template>
  <div class="import-container">
    <div class="app-container">
      <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
    </div>
  </div>
</template>

<script>
import { reqImportEmployee } from '@/api/employees'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$router.query.type
    }
  },
  methods: {
    // 读取文件之前的校验
    beforeUpload(file) {
      console.log(file)
      return true
    },
    async  handleSuccess({ results, header }) {
      if (this.type === 'user') {
        // header中, results中的数据是中文的, 但是提交给后台的要是英文的
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
        // 遍历 results 每一行的Excel数据都要处理，将中文转换成英文的键

        const arr = results.map(item => {
          const obj = {}
          header.forEach(key => {
            const englishkey = userRelations[key]
            if (['timeOfEntry', 'correctionTime'].includes(englishkey)) {
              obj[englishkey] = this.formatExcelDate(item[key], '-')
            } else {
              obj[englishkey] = item[key]
            }
          })
          return obj
        })

        await reqImportEmployee(arr)
        this.$message.success('导入成功')
        this.$router.back()
      }
    },
    // 转换excel的日期格式
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>
